package com.boot.security.server.hitapp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.boot.security.server.dao.AppPaymentOrderDao;
import com.boot.security.server.dao.AppTradePaynoDao;
import com.boot.security.server.dao.AppVisitPayDao;
import com.boot.security.server.dto.AjaxJsonVo;
import com.boot.security.server.model.AppPaymentOrder;
import com.boot.security.server.model.AppTradePayno;
import com.boot.security.server.model.AppVisitPay;
import com.boot.security.server.utils.AppConstants;
import com.jpay.alipay.AliPayApi;
import com.jpay.alipay.AliPayApiConfig;
import com.jpay.alipay.AliPayApiConfigKit;
import com.jpay.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Slf4j
public class AliPayController {

    @Value("${alipay.appId}")
    private String appId = "2016092500595538";
    @Value("${alipay.privateKey}")
    private String privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCKVn/mxmT7Xwglxz5OwBN1KOLoGlZAzQgcYQQ5HxS0ih7oD3mAWl0i/mT6ZMUoVm1+T8EqCxnK6yZpxj5NuQwaKSKeLhkRij/4lE6fjiZ1jn60cF4tfdqTQCUxLyHAjavxs1RmI6jWnliOxzT5Irf2StlaDpSx6Okp6TZLugYSx/vnhIzrcfCiiXiCaZvFXFHSGw9cKo6o/kQxeOG43BFXI0RrF2ce6sy8tTAXlgwM1SZD7GprUHE9hR+zNaNjgeHIOF/Qn44CFD09p/x/MB5LKNGOiOGmIiVghzIcCDIgrSN2itW4N5pwnTV5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HjtkIECgYEAhd2BiLZSIL9PwVX/TqvZMXUbewOuRNurAUCpd6llfMJ6q0+wSajYrrjRZyNKUwfJGjQCMCfBTXv0EQ2q/ElYtVDLwSyFql3B8BoaZ5RsCpIw26WyKuU5JQpb70Vz9j7/cDEhc8pFCIlNn2I/wN6GlkjVrX4rlvy2vExNkhD4e+k=";
    @Value("${alipay.publicKey}")
    private String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsxXL5a8xTpUlE2iQCnfyBx/tZG1PayxC+FitzlKJiDRP5IDLVcap/1r8x2ybEpQjHxQD+8Q7vXY1aCcKeHYQPiY34N8uzL/i+ROUFv722/l3BaEsMHcDyKanD8vyCtsZ6+6HmtaoExkRylMC+P0t9hQr/03s71lbcZ8gRVJTH9oiVsiws5SZyP3vtzJYUYv43YqS3PiE7VAT6dbc6RF5LXUOan+nFbou7Ji/Wc21zgovk6cb9A+bpFHeXNKjZpnze5CtGmH7IrsAqhmBGW9OB8u387qgUuJTlRdtMzBaJV/HZVRX1wZcFZnDZ0mNcCl9dr61W8S0kbg10cPn2t6eaQIDAQAB";
    @Value("${alipay.serverUrl}")
    private String serverUrl="https://openapi.alipaydev.com/gateway.do";
    @Value("${alipay.domain}")
    private String notify_domain="http://zll.huaxiadaowei.com";

    private  String charset = "UTF-8";

    private  String sign_type = "RSA2";

    @Autowired
    private AppTradePaynoDao appTradePaynoDao;
    @Autowired
    private AppPaymentOrderDao appPaymentOrderDao;
    @Autowired
    private AppVisitPayDao appVisitPayDao;

    public AliPayApiConfig getApiConfig() {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(appId);
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.New()
                    .setAppId(appId)
                    .setAlipayPublicKey(publicKey)
                    .setCharset(charset)
                    .setPrivateKey(privateKey)
                    .setServiceUrl(serverUrl)
                    .setSignType(sign_type)
                    .build();
        }
        return aliPayApiConfig;
    }

    /**
     * 扫码支付
     */
    public AjaxJsonVo tradePrecreatePay(AppTradePayno appTradePayno) {
        AjaxJsonVo aj = new AjaxJsonVo();
        aj.setSuccess(false);
        String orderId =appTradePayno.getOuttradeno();
        if (StringUtils.isAnyBlank(orderId)){
            aj.setMsg("支付失败,支付所需参数缺失");
            return aj;
        }
        String return_msg = "统一订单失败";

        AliPayApiConfig aliPayApiConfig=getApiConfig();
        AliPayApiConfigKit.setThreadLocalAliPayApiConfig(aliPayApiConfig);
        //商品描述
        String subject = appTradePayno.getSubject()==null? "诊疗服务费用":appTradePayno.getSubject();
        //String storeId = "2088102177252500";//商户门店编号
        String notifyUrl = notify_domain + "/alipay/precreate_notify_url";

        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setSubject(subject);//	订单标题
        model.setBody(subject);//	对交易或商品的描述
        model.setTotalAmount(appTradePayno.getTotalamount());//	订单总金额，单位为元，精确到小数点后两位，取值范围[0.01,100000000]
        //model.setStoreId(storeId);//	商户门店编号
        model.setTimeoutExpress("30m");//该笔订单允许的最晚付款时间 m-分钟，h-小时，d-天
        model.setOutTradeNo(orderId);//商户订单号
        model.setQrCodeTimeoutExpress("90m");//该笔订单允许的最晚付款时间，逾期将关闭交易，从生成二维码开始计时。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
        try {
            String resultStr = AliPayApi.tradePrecreatePayToResponse(model, notifyUrl).getBody();
            System.out.println(resultStr);
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            jsonObject=jsonObject.getJSONObject("alipay_trade_precreate_response");
            if(jsonObject.getString("code").equals("10000")){
                String qr_code = jsonObject.getString("qr_code");
                Map<String, String> returnMap = new HashMap<String, String>();
                returnMap.put("code_url",qr_code);
                aj.setObj(returnMap);
                aj.setMsg("操作成功");
                aj.setSuccess(true);
            }else{
                aj.setMsg(jsonObject.getJSONObject("alipay_trade_precreate_response").getString("sub_msg"));
            }
        } catch (Exception e) {
            log.error(Thread.currentThread().getStackTrace()[1].getMethodName() +"发生的异常是: ",e);
            aj.setMsg("支付下单失败,请稍后再试");
        }
        return aj;
    }

    public static void main(String[] args) {
        AliPayController ali=new AliPayController();
        AppTradePayno payno=new AppTradePayno();
        payno.setSubject("诊疗服务费用");
        payno.setOuttradeno("201904080022001");
        payno.setTotalamount("0.1");
        System.out.println(JSON.toJSONString(ali.tradePrecreatePay(payno)));
    }
    //支付通知
    @PostMapping("/precreate_notify_url")
    public String  aliPayNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> map = AliPayApi.toMap(request);
            /*for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println(entry.getKey()+" = "+entry.getValue());
            }*/
            //验证签名
            boolean flag = AlipaySignature.rsaCheckV1(map, publicKey, charset,
                    sign_type);
            if (flag) {//验证成功时
                if("TRADE_SUCCESS".equals(map.get("trade_status"))){ //交易成功
                    String out_trade_no=map.get("out_trade_no");
                    AppTradePayno appTradePayno=appTradePaynoDao.getByOuttradeno(out_trade_no);
                    String status=appTradePayno.getFeestatus();
                    //判断订单状态，修改状态
                    if(status.equals(AppConstants.FEE_STATUS_DEFAULT)){
                        log.warn("更新订单信息" );
                        appTradePayno.setNotifyid(map.get("notify_id"));
                        appTradePayno.setNotifytime(map.get("notify_time"));
                        appTradePayno.setFeestatus(AppConstants.FEE_STATUS_YZF);
                        appTradePayno.setOrderstatus(AppConstants.ORDER_STATUS_SUCCESS);
                        appTradePaynoDao.update(appTradePayno);
                        AppPaymentOrder order=new AppPaymentOrder();
                        order.setTradeno(appTradePayno.getTradeno());
                        order=appPaymentOrderDao.getBylist(order);
                        order.setPaystaus(AppConstants.ORDER_STATUS_SUCCESS);
                        appPaymentOrderDao.update(order);
                        //修改缴费记录缴费状态
                        AppVisitPay appVisitPay=new AppVisitPay();
                        appVisitPay.setTradeno(appTradePayno.getTradeno());
                        appVisitPay=appVisitPayDao.findInfo(appVisitPay);
                        appVisitPay.setPaystaus(AppConstants.ORDER_STATUS_SUCCESS);
                        appVisitPayDao.update(appVisitPay);
                    }
                    System.out.println("precreate_notify_url success");
                    return "success";
                }else{
                    return "failure";
                }
            } else {
                System.out.println("precreate_notify_url failure");
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }
}
